package cn.exam.sys.servlets;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import cn.exam.common.PageControl;
import cn.exam.common.Pager;
import cn.exam.common.Tools;
import cn.exam.model.Paper;
import cn.exam.model.Subject;
import cn.exam.sys.services.impl.PaperService;
import cn.exam.sys.services.interfaces.IPaperService;

public class PaperServlet extends HttpServlet {
	IPaperService service = new PaperService();
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	
		String cmd = request.getParameter("cmd");
		if(cmd.equals("add")){
			addsubject(request,response);
		}else if(cmd.equals("list")){
			list(request,response);
		}else if(cmd.equals("slist")){
			slist(request,response);
		}else if (cmd.equals("delete")) {  // 添加此部分
			deletePaper(request, response);
		}
	}	
	
	/**
	 * 生成试题功能
	 * @param request
	 * @param response
	 */
	private void addsubject(HttpServletRequest request, HttpServletResponse response) {
		Paper paper = new Paper();
		try {
			BeanUtils.populate(paper, request.getParameterMap());
			paper.setDifficulty(request.getParameter("difficulty"));
			paper.setCategory(request.getParameter("category"));

			String[] selectedSubjects = request.getParameterValues("selectedSubjects");

			// 生成唯一试卷号（自动、手动都需要）
			String pno = String.valueOf(System.currentTimeMillis());
			paper.setPno(pno);

			Integer rtn = 0;

			if (selectedSubjects != null && selectedSubjects.length > 0) {
				// 👇 是手动组卷：先创建空试卷记录（只插入基本信息，不含题目）
				for (String sid : selectedSubjects) {
					Integer subjectId = Integer.parseInt(sid);
					service.addSubjectToPaper(paper, subjectId); // 插入题目
				}
				rtn = 1; // 手动组卷成功
			} else {
				// 👇 是自动组卷：自动创建试卷并自动加题
				rtn = service.addpaper(paper);
			}

			if (rtn <= 0) {
				request.setAttribute("msg", "创建试卷失败！");
				request.getRequestDispatcher("/sys/paper/add.jsp").forward(request, response);
				return;
			}

			response.sendRedirect(Tools.Basepath(request, response) + "sys/paper?cmd=list");

		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("msg", "操作失败：" + e.getMessage());
			try {
				request.getRequestDispatcher("/sys/paper/add.jsp").forward(request, response);
			} catch (ServletException | IOException ex) {
				throw new RuntimeException(ex);
			}
		}
	}
	/**
	 * 删除试卷功能
	 */
	private void deletePaper(HttpServletRequest request,HttpServletResponse response){
		String pno = request.getParameter("id"); // 直接获取字符串
		System.out.println("Attempting to delete paper with PNO: " + pno); // 调试日志
		Integer rtn = service.deletePaper(pno); // 传递字符串给服务层
		System.out.println("Delete result: " + rtn); // 输出删除结果
		if(rtn>0){
			try {
				response.sendRedirect(Tools.Basepath(request,response)+
						"sys/paper?cmd=list");
			}catch (IOException e){
				e.printStackTrace();
			}
		}else {
			try {
				request.setAttribute("msg","删除试卷失败!");
				request.getRequestDispatcher("/sys/paper/list.jsp").forward(request,response);
			}catch (ServletException | IOException e){
				e.printStackTrace();
			}
		}
	}
	/**
	 * 查询试题列表
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void list(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String pname = request.getParameter("pname");
		Paper paper = new Paper();
		if(pname!=null && !pname.equals("")){
			paper.setPname(pname);
		}
		PageControl pc = new PageControl();
		Integer currindex = 1;
		if(request.getParameter("index")!=null){
			currindex = Integer.parseInt(request.getParameter("index"));
		}
		pc.setCurrentindex(currindex);
		pc.setPagesize(10);
		Pager<Paper> pager = service.list(paper, pc);
//		System.out.println(pager.getList());;
		request.setAttribute("pager", pager);
		request.getRequestDispatcher("/sys/paper/list.jsp").forward(request, response);
	}
	private void slist(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Paper paper = new Paper();
		String pno = request.getParameter("pno");
		paper.setPno(pno);
		List<Subject> subjects = service.subjectlist(paper);
		request.setAttribute("subjects", subjects);
		request.getRequestDispatcher("/sys/paper/subjects.jsp").forward(request, response);
	}
}
